package models

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"

	"ssnotify/common/constant"
	cDto "ssnotify/common/dto"
	"ssnotify/common/enums/notifyread"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models/query"
)

type NotifyRecord struct {
	Id         string         `json:"id" gorm:"type:varchar(64)"`
	Status     string         `json:"status" gorm:"type:varchar(10);comment:通知状态：未发送、发送成功、发送失败"`
	CreateTime cDto.LocalTime `json:"createTime" gorm:"type:datetime;comment:通知产生时间"`
	DeptId     string         `json:"deptId" gorm:"type:varchar(64);comment:通知分组id"`
	UserId     string         `json:"userId" gorm:"type:varchar(64);comment:通知用户id"`
	OriginId   string         `json:"originId" gorm:"type:varchar(64);comment:来源id，告警为告警id"`
	Content    string         `json:"content" gorm:"type:longtext;comment:通知内容(数据模型json或组装后内容string)"`
	Type       string         `json:"type" gorm:"type:varchar(128);comment:通知类型"`
	ConfigId   string         `json:"configId" gorm:"type:varchar(64);comment:配置id"`
	Sn         string         `json:"sn" gorm:"type:varchar(64);comment:设备sn"`
	ReadStatus string         `json:"readStatus" gorm:"type:varchar(10);comment:阅读状态 1：未读，2：已读"`
	UserName   string         `json:"userName" gorm:"type:varchar(64);comment:发送用户名"`
	AgencyId   string         `json:"agencyId" gorm:"type:varchar(64);comment:机构用户id"`
	SendWay    string         `json:"sendWay" gorm:"type:varchar(10);comment:发送方式"`
	DevType    string         `json:"devType" gorm:"type:varchar(20);comment:设备类型"`
	SendErr    string         `json:"sendErr" gorm:"type:text;comment:发送异常信息"`

	model.Model

	DevName string `json:"devName" gorm:"-"`
}

func (NotifyRecord) TableName() string {
	return "sys_notify_record"
}

func (e *NotifyRecord) Generate() *NotifyRecord {
	o := *e
	return &o
}

func (e *NotifyRecord) FindNotifyRecordList(req *query.NotifyRecordQuery) (err error, result interface{}) {
	list := make([]NotifyRecord, 0)
	var count int64
	devCache, _ := env.Cache.HashGetAll(constant.DeviceEasyCache)
	deviceName := make(map[string]string)
	for sn, cachestr := range devCache {
		deviceName[sn] = utils.BytesToMap([]byte(cachestr))["name"].(string)
	}
	if req.PageIndex > 0 && req.PageSize > 0 {
		err = e.FindPage(&list, &count,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("create_time", true, req.OrderBy),
			cDto.Paginate(req.GetPageSize(), req.GetPageIndex()),
		)
		for i := range list {
			if len(list[i].Sn) > 0 {
				if name, ok := deviceName[list[i].Sn]; ok {
					list[i].DevName = name
				}
			}
		}
		result = &cDto.Page{
			Records:   list,
			Total:     count,
			PageSize:  req.GetPageSize(),
			PageIndex: req.GetPageIndex(),
			Pages:     (count + int64(req.GetPageSize()) - 1) / int64(req.GetPageSize()),
			Other:     nil,
		}
	} else {
		for i := range list {
			if len(list[i].Sn) > 0 {
				if name, ok := deviceName[list[i].Sn]; ok {
					list[i].DevName = name
				}
			}
		}
		err = e.FindList(&list,
			cDto.MakeCondition(req.GetNeedSearch()),
			cDto.OrderDest("create_time", true, req.OrderBy),
		)
		result = list
	}
	return
}

func (e *NotifyRecord) FindNotifyRecordCount(req *query.NotifyRecordQuery, count *int64) (err error) {
	err = e.FindCount(e, count, cDto.MakeCondition(req.GetNeedSearch()))
	return
}

func (e *NotifyRecord) ReadNotifyRecord(userId string, id *string) error {
	c := query.NotifyRecordQuery{}
	c.UserIdEq = userId
	if id != nil && len(*id) > 0 {
		c.IdIn = strings.Split(strings.ReplaceAll(*id, " ", ""), ",")
	}
	if err := e.ModMap(e, map[string]interface{}{"read_status": notifyread.Read.Get().Key}, cDto.MakeCondition(c.GetNeedSearch())); err != nil {
		return err
	}
	return nil
}
